import { _decorator, Component, Node, sp } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('SpineComponent')
export class SpineComponent extends Component {
    private spine?: sp.Skeleton;
    onLoad() {
        this.spine = this.getComponent('sp.Skeleton') as sp.Skeleton;
    }
    play(animation: string, speed: number = 1, loop: boolean = false) {
        this.spine?.setToSetupPose();
        this.spine?.setAnimation(0, animation, loop);
        this.spine.timeScale = speed;
    }
    stop() {
        this.spine?.clearTrack(0);
    }
    pause() {
        this.spine.paused = true;
    }
    resume() {
        this.spine.paused = false;
    }
    addStartListener(callback: (trackEntry) => void) {
        this.spine?.setStartListener(callback);
    }

    addEndListener(callback: (trackEntry) => void) {
        this.spine?.setEndListener(callback);
    }

    addCompleteListener(callback: (trackEntry) => void) {
        this.spine?.setCompleteListener(callback);
    }
    backPlay(animation: string, callback: Function = null, speed: number = 1, loop: boolean = false) {
        let track = this.spine.setAnimation(0, animation, loop);
        track.trackTime = track.animationEnd;
        this.spine.timeScale = -1 * speed;
        if (callback)
            this.scheduleOnce(callback, (track.animation.duration - 0.5) / speed)
    }
    backPlayNow(callback: Function = null, speed: number = 1, loop: boolean = false) {
        this.spine.timeScale = -1 * speed;
        let track = this.spine.getCurrent(0);
        if (callback)
            this.scheduleOnce(callback, (track.animation.duration - 0.5) / speed)
    }
    setColor(color) {
        this.spine.color = color;
    }
}

